//
//  QSShareView.swift
//  TestSwift
//
//  Created by Song on 2018/7/3.
//  Copyright © 2018年 Song. All rights reserved.
//

import UIKit

/// cell的注册时的Id
let shareViewCellID = "shareViewCellID"

class QSShareView: UIView, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
    // 子控件
    var contentView: UIView?
    var collectionview: UICollectionView?
    
    // 属性
    var dataArray: Array<UMSocialPlatformType>?
    // 分享内容
    var title: String?          // 标题
    var desc: String?           // 描述
    var thumbImg: Any?          // 缩略图
    var webPageUrl: String?     // 网页地址
    var shareImg: Any?          // 分享图片
    
    var shareType: QSShareModeType? // 分享类型
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.setupSubViews()
    }
    
    convenience init(with shareTypeArray: Array<UMSocialPlatformType>, type: QSShareModeType? = .WebPage, title: String? = "", desc: String? = "", thumbImg: Any? = nil, webUrl: String? = "", shareImg: Any? = nil) {
        self.init(frame: UIScreen.main.bounds)
        
        self.shareType = type
        self.title = title
        self.desc = desc
        self.thumbImg = thumbImg
        self.webPageUrl = webUrl
        self.shareImg = shareImg
        
        self.showShareView(withTypeArray: shareTypeArray)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupSubViews() {
        self.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5)
        self.alpha = 0.0
        
        // contentView
        contentView = UIView.init()
        self.addSubview(contentView!)
        contentView?.snp.makeConstraints({ (make) in
            make.left.right.equalTo(0.0)
            make.bottom.equalTo(200.0)
            make.height.equalTo(200.0)
        })
        
        contentView?.backgroundColor = kWhiteColor
        
        // cancelBtn
        let cancelBtn = UIButton.init()
        contentView?.addSubview(cancelBtn)
        cancelBtn.snp.makeConstraints { (make) in
            make.left.bottom.right.equalTo(0.0)
            make.height.equalTo(50.0)
        }
        
        cancelBtn.setTitle("取消", for: UIControlState.normal)
        cancelBtn.setTitleColor(UIColor.black, for: UIControlState.normal)
        cancelBtn.titleLabel?.font = UIFont.systemFont(ofSize: 17.0)
        cancelBtn.addTarget(self, action: #selector(self.clickCancelBtn(btn:)), for: .touchUpInside)
        
        // lineView
        let lineView = UIView.init()
        contentView?.addSubview(lineView)
        lineView.snp.makeConstraints { (make) in
            make.left.right.equalTo(0.0)
            make.bottom.equalTo(cancelBtn.snp.top).offset(0.0)
            make.height.equalTo(1.0)
        }
        
        lineView.backgroundColor = UIColor.init(red: 187.0, green: 187.0, blue: 187.0, alpha: 1.0)
        
        // collectionview
        let flowLayout = UICollectionViewFlowLayout.init()
        collectionview = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: flowLayout)
        contentView?.addSubview(collectionview!)
        collectionview!.snp.makeConstraints { (make) in
            make.top.left.right.equalTo(0.0)
            make.bottom.equalTo(lineView.snp.top).offset(0.0)
        }
        
        flowLayout.itemSize = CGSize.init(width: (UIScreen.main.bounds.width - 30.0) / CGFloat(kLineCount), height: 109.0)
        flowLayout.minimumLineSpacing = 0;
        flowLayout.minimumInteritemSpacing = 0;
        
        collectionview!.backgroundColor = UIColor.clear
        collectionview!.delegate = self;
        collectionview!.dataSource = self;
        collectionview!.contentInset = UIEdgeInsetsMake(15.0, 15.0, 15.0, 15.0)
        
        // 注册
        collectionview!.register(QSShareViewCell.classForCoder(), forCellWithReuseIdentifier: shareViewCellID)
    }
    
    // MARK: - Private Methods
    /// 显示
    func showShareView(withTypeArray: Array<UMSocialPlatformType>) {
        if !kSystemShare {
            // 系统自带分享
            QSUMengManager.qs_showSystemShareView(title: self.title, thumbImg: self.thumbImg, webPageUrl: self.webPageUrl)
            
            return
        }
        
        // 判断是否支持该分享平台
        var tempArr = withTypeArray
        for itemType in tempArr {
            let isInstall = UMSocialManager.default().isInstall(itemType)
            let isSupport = UMSocialManager.default().isSupport(itemType)
            
            if !isInstall || !isSupport {
                tempArr.remove(at: tempArr.index(of: itemType)!)
            }
        }
        
        self.dataArray = Array.init(tempArr)
        
        if self.dataArray != nil && (self.dataArray?.count)! > 0 {
            let keyWindow = UIApplication.shared.keyWindow
            keyWindow?.addSubview(self)
            self.snp.makeConstraints { (make) in
                make.top.left.right.bottom.equalTo(0.0)
            }
            
            // 重新设置控件高度
            self.contentView?.snp.updateConstraints({ (make) in
                make.height.equalTo(109.0 * CGFloat(((self.dataArray?.count)! / kLineCount + ((self.dataArray?.count)! % kLineCount > 0 ? 1 : 0))) + (51.0 + 30.0))
                make.bottom.equalTo(109.0 * CGFloat(((self.dataArray?.count)! / kLineCount + ((self.dataArray?.count)! % kLineCount > 0 ? 1 : 0))) + (51.0 + 30.0))
            })
            
            self.collectionview?.reloadData()
            
            // 动画
            self.contentView?.superview?.layoutIfNeeded()
            UIView.animate(withDuration: 0.35, animations: {
                self.contentView?.snp.updateConstraints({ (make) in
                    make.bottom.equalTo(0.0)
                })
                
                self.alpha = 1.0
                self.contentView?.superview?.layoutIfNeeded()
            })
        } else {
            QSHud.qs_showText(title: "请安装社交通讯软件进行分享！")
        }
    }
    
    /// 点击取消
    @objc private func clickCancelBtn(btn: UIButton) {
        self.dismissShareView()
    }
    
    /// 隐藏
    private func dismissShareView() {
        // 动画
        self.contentView?.superview?.layoutIfNeeded()
        UIView.animate(withDuration: 0.35, animations: {
            self.contentView?.snp.updateConstraints({ (make) in
                make.bottom.equalTo(109.0 * CGFloat(((self.dataArray?.count)! / kLineCount + ((self.dataArray?.count)! % kLineCount > 0 ? 1 : 0))) + (51.0 + 30.0))
            })
            
            self.alpha = 0.0
            self.contentView?.superview?.layoutIfNeeded()
        }) { (finish) in
            self.removeFromSuperview()
        }
    }
    
    // MARK: - UICollectionViewDataSource
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if (self.dataArray) != nil {
            return (self.dataArray?.isEmpty)! ? 0 : (self.dataArray?.count)!
        }
        
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: shareViewCellID, for: indexPath) as! QSShareViewCell
        
        cell.setSharePlatform(self.dataArray![indexPath.item])
        
        return cell
    }
    
    // MARK: - UICollectionViewDelegateFlowLayout
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let platform = self.dataArray![indexPath.item]
        
        switch self.shareType! {
        case .WebPage:
            QSUMengManager.qs_shareWebPage(platformType: platform, title: self.title, desc: self.desc, thumbImg: self.thumbImg, webPageUrl: self.webPageUrl)
            
        case .Image:
            QSUMengManager.qs_shareImage(platformType: platform, thumbImg: self.thumbImg, shareImg: self.shareImg)
        }
        
        // 退出分享的view
        self.dismissShareView()
    }
}
